import { HASH_CHUNK_SIZE, blobSlice } from '../index';
const THREAD_COUNT = navigator.hardwareConcurrency || 4; // 默认线程基数
export function useThreadService() {
  let currentTask = false; // 当前任务空闲标志
  const taskQueue = []; // 任务队列

  const hanldeThreadTask = (file, onProgress) => {
    return new Promise((resolve) => {
      const result = [];
      let progress = 0;
      const chunkSize = Math.ceil(file.size / HASH_CHUNK_SIZE / THREAD_COUNT) * HASH_CHUNK_SIZE;
      const threadCount = Math.ceil(file.size / chunkSize);

      for (let index = 0; index < threadCount; index++) {
        // 创建切片
        const startIndex = Math.min(index * chunkSize, file.size);
        const endIndex = Math.min(startIndex + chunkSize, file.size);
        const chunkFile = blobSlice.call(file, startIndex, endIndex, file.type);

        // 创建线程
        const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
        // 发送线程消息
        worker.postMessage({ file: chunkFile });

        worker.onmessage = (e) => {
          result[index] = e.data; // 保存线程处理结果
          worker.terminate(); // 结束线程
          progress += endIndex - startIndex;
          onProgress?.(progress, file.size);
          // 返回结果
          progress === file.size && resolve(result.flat());
        };
      }
    });
  };

  function chunkThreadTask(...args) {
    if (currentTask) {
      return new Promise((resolve) => taskQueue.push(() => resolve(chunkThreadTask(...args))));
    }

    const onNext = () => {
      currentTask = false;
      const nextTaskQueue = taskQueue.shift();
      nextTaskQueue && nextTaskQueue();
    };

    return hanldeThreadTask(...args).finally(onNext);
  }

  return { threadCount: THREAD_COUNT, chunkThreadTask };
}
